<?php
class Gangnet_Model_GnUserMapper
{
    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Gangnet_Model_GnUser_GnUser');
        }
        return $this->_dbTable;
    }

    public function save(Gangnet_Model_GnUser $user)
    {
        $data = array(
            'account' => $user->getAccount(),
            'password' => $user->getPassword(),
            'name'   => $user->getName(),
            'roster_pd1' => $user->getRosterPD1(),
            'roster_pd2' => $user->getRosterPD2(),
            'specialization' => $user->getSpecialization(),
            'skills_link' => $user->getSkillsLink(),
            'games_owned' => $user->getGamesOwned()
        );

        if (null === ($id = $user->getId())) {
            unset($data['id']);
            $this->getDbTable()->insert($data);
        } else {
            $this->getDbTable()->update($data, array('id = ?' => $id));
        }
    }

    public function find($id, Gangnet_Model_GnUser $user)
    {
        $result = $this->getDbTable()->find($id);
        if (0 == count($result)) {
            return;
        }
        $row = $result->current();
        $user->setId($row->id)
            ->setAccount($row->account)
            ->setPassword($row->password)
            ->setName($row->name)
            ->setRosterPD1($row->roster_pd1)
            ->setRosterPD2($row->roster_pd2)
            ->setSpecialization($row->specialization)
            ->setSkillsLink($row->skills_link)
            ->setGamesOwned($row->games_owned);
    }

    public function fetchAll()
    {
        $resultSet = $this->getDbTable()->fetchAll();
        $entries   = array();
        foreach ($resultSet as $row) {
            $entry = new Gangnet_Model_GnUser();
            $entry->setId($row->id)
                ->setAccount($row->account)
                ->setPassword($row->password)
                ->setName($row->name)
                ->setRosterPD1($row->roster_pd1)
                ->setRosterPD2($row->roster_pd2)
                ->setSpecialization($row->specialization)
                ->setSkillsLink($row->skills_link)
                ->setGamesOwned($row->games_owned);
            $entries[] = $entry;
        }
        return $entries;
    }
}